package com.qf.controller;
import com.qf.Constant.AuthConstant;
import com.qf.Constant.CarConstant;
import com.qf.entity.Goods;
import com.qf.entity.User;
import com.qf.feign.GoodService;
import com.qf.result.Result;
import com.qf.vo.Car;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/16/20:29
 * @Description:
 */
@Controller
@RequestMapping("/car")
public class CarController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GoodService goodService;
    /*static {
        ParserConfig.getGlobalInstance().addAccept("shop-07-common/src/main/java/com/qf/entity");
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }*/
  @RequestMapping("/add")
  @ResponseBody
    public Result addCar(Car car,HttpSession session, HttpServletResponse response, @CookieValue(name = CarConstant.ANNIO_CAR_COOKIE_NAME,defaultValue = "") String anoId){
      // 1.获取当前登录的用户
       User user = (User) session.getAttribute(AuthConstant.AUTH_SESSION);
      // 2.创建一个Map和reids绑定
      BoundHashOperations<String, Object, Object> hashOps=null;
      if (user!=null) {
          Integer uid = user.getId();
          hashOps = redisTemplate.boundHashOps(CarConstant.USERCARPRE + uid);
      }else {
          if (StringUtils.isEmpty(anoId)) {
               anoId = UUID.randomUUID().toString();
              Cookie cookie = new Cookie(CarConstant.ANNIO_CAR_COOKIE_NAME,anoId);
              cookie.setMaxAge(60*60*24);
              cookie.setPath("/");
              response.addCookie(cookie);
          }
       hashOps=redisTemplate.boundHashOps(CarConstant.USERCARPRE+anoId);
      }
    hashOps.put(car.getGid().toString(),car.getSum().toString());
      return Result.success();

  }
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(){
      return Result.success();
    }
    @RequestMapping("update")
    @ResponseBody
    public Result updateCar(String gid,HttpSession httpSession,String type,@CookieValue(name = CarConstant.ANNIO_CAR_COOKIE_NAME,defaultValue ="") String anoId){
      User user = (User) httpSession.getAttribute(AuthConstant.AUTH_SESSION);
        BoundHashOperations<String, Object, Object> carMap=null;
        if(user!=null){
            Integer uid = user.getId();
            carMap = redisTemplate.boundHashOps(CarConstant.USERCARPRE + uid);
        }else {
            if(!StringUtils.isEmpty(anoId)){
                carMap = redisTemplate.boundHashOps(CarConstant.USERCARPRE + anoId);
            }
        }
        //判断是增还是减
        switch (type){
            case CarConstant.CAR_TYPE_INCR:
                carMap.increment(gid,1);
                break;
            case CarConstant.CAR_TYPE_DEL:
                Integer num = Integer.parseInt(carMap.get(gid).toString());
                carMap.put(gid,(--num)+"");
                break;
        }
        return Result.success();
  }
  //合并购物车
     @RequestMapping("/mergeCar{uid}/anoId}")
     @ResponseBody
    public Result mergeCar(@PathVariable Integer uid, @PathVariable String anoId) {
         BoundHashOperations<String, Object, Object> uidCarMap = redisTemplate.boundHashOps(CarConstant.USERCARPRE + uid);
         BoundHashOperations<String, Object, Object> anoIdCarMap = redisTemplate.boundHashOps(CarConstant.USERCARPRE + anoId);
         //遍历anoIdCarMap
         Map<Object, Object> entries = anoIdCarMap.entries();
         Set<Map.Entry<Object, Object>> entrySet = entries.entrySet();
         for (Map.Entry<Object, Object> entry : entrySet) {
             Object key = entry.getKey();
             Object value = entry.getValue();
             if (uidCarMap.hasKey(key)){
                 //合并已登录和未登录的购物车
                 Integer unum = Integer.parseInt(uidCarMap.get(key).toString());
                 Integer anInt = Integer.parseInt(value.toString());
                value=unum+anInt;
             }
             uidCarMap.put(key,value);
         }
         //删除未登录的购物车key
         redisTemplate.delete(CarConstant.USERCARPRE+anoId);
         return Result.success();
     }
     @RequestMapping("/list")
     //获取购物车列表
   public String getCarList(HttpSession session, ModelMap modelMap,@CookieValue(name = CarConstant.ANNIO_CAR_COOKIE_NAME,defaultValue = "") String anoId){
      //查看用户是否已登录
         User user = (User) session.getAttribute(AuthConstant.AUTH_SESSION);
         BoundHashOperations<String, Object, Object> carMap=null;
       if (user!=null) {
           Integer uid = user.getId();
          carMap = redisTemplate.boundHashOps(CarConstant.USERCARPRE + uid);
       }else {
           if (StringUtils.isNotEmpty(anoId)) {
               carMap = redisTemplate.boundHashOps(CarConstant.USERCARPRE + anoId);
           }
       }
         BigDecimal totalPrice = new BigDecimal(0.0);
         //创建list集合
       List<Car> carList=new ArrayList<>();
       //遍历购物车
         if (carMap!=null) {
             Map<Object, Object> entries = carMap.entries();
             for (Map.Entry<Object, Object> entry : entries.entrySet()) {
                 Object key1 = entry.getKey();
                 Integer key = Integer.parseInt(key1.toString());
                 Object value1 = entry.getValue();
                 Integer value = Integer.parseInt(value1.toString());
                 Car car = new Car();
                 car.setGid(key);
                 car.setSum(value);
                 Goods goods = goodService.info(key);
                 car.setGoods(goods);
                 //计算商品总价
                 BigDecimal total = goods.getGprice().multiply(BigDecimal.valueOf(value));
                 car.setSubTotal(total);
                 carList.add(car);
               totalPrice = totalPrice.add(total);
             }
             modelMap.put("carList",carList);
             modelMap.put("totalPrice", totalPrice);
           }
           return "carList";
  }
    @RequestMapping("/getCarListByUidAndGid")
    @ResponseBody
  public  Map<String, Object> getCarListByUidAndGid(@RequestParam ("uid")Integer uid, @RequestParam("carGidArray") List<String> carGidArray){
        Map<String, Object> map = getCar(carGidArray, uid);
        return map;

    }
    @RequestMapping("/getCarListByUid/{uid}")
    @ResponseBody
    public Map<String, Object> getCarListByUid(@PathVariable Integer uid){
        Map<String, Object> map = getCar(null, uid);
        return map;
    }

    public   Map<String, Object> getCar(List<String> carGidArray,Integer uid){
        List<Car> carList = new ArrayList<>();
        BigDecimal totalPrice = new BigDecimal(0.0);
        //查询购物车
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(CarConstant.USERCARPRE+uid);
        //判断用户是否勾选
        if (carGidArray!=null&&carGidArray.size()>0) {
            for (String gid : carGidArray) {
                System.out.println("商品id为:"+gid);
                String sum = (String) ops.get(gid);
                System.out.println("商品数量为:"+sum);
                //封装car对象
                toCarObject(carList,gid,sum);
            }
        }else {
            Map<Object, Object> entries = ops.entries();
            Set<Map.Entry<Object, Object>> entrySet = entries.entrySet();
            for (Map.Entry<Object, Object> entry : entrySet) {
                String key = (String) entry.getKey(); // gid
                String value = (String) entry.getValue(); // sum
                toCarObject(carList, key, value);
            }
        }
        for (Car car : carList) {
            totalPrice = totalPrice.add(car.getSubTotal());
        }
        // 4.返回购物车和总结
        Map<String, Object> map = new HashMap<>();
        map.put("carList", carList);
        map.put("totalPrice", totalPrice);

        return map;
    }
    public void toCarObject(List<Car> carList, String key, String value) {
        // 创建对象
        Car car = new Car();

        // 类型转换
        int gid = Integer.parseInt(key);
        int sum = Integer.parseInt(value);
        // 3.查询商品的信息
        Goods goods =goodService.info(gid);
        // 4.封装
        car.setGid(gid);
        car.setSum(sum);
        car.setGoods(goods);
        // 5.计算小计
        BigDecimal subTotal = goods.getGprice().multiply(BigDecimal.valueOf(sum));
        car.setSubTotal(subTotal);
        carList.add(car);
    }
}
